<template>
  <div>
    <box t1="权限管理" t2="角色列表">
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="roleList">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 权限下树状结构 -->
            <el-row
              :class="['bdbottom',i1===0?'bdtop':'','vcenter']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限菜单的显示列 -->
              <el-col :span="5">
                <el-tag closable @close="removeRoleById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二三级权限菜单的显示列 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                  :class="[i2===0?'':'bdtop','vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRoleById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      @close="removeRoleById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </box>
    <!-- 分配权限的弹出框 -->
    <el-dialog title="分配权限" :visible.sync="rightsDialogVisible" width="50%">
      <!-- 树形控件 -->
      <!-- @node-click="handleNodeClick" -->
      <!-- show-checkbox 展示复选框 -->
      <!-- node-key="id"指定每一个节点的值 -->
      <el-tree
        :data="rightslist"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="leafKeysArry"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      rightsDialogVisible: false,
      rightslist: [],
      treeProps: {
        // label表示树形菜单显示的内容 来源于数据源的哪一个属性
        // children表示树形菜单的下一层数据 来自于数据源的哪一个属性
        label: "authName",
        children: "children"
      },
      leafKeysArry: [],
      roleId: ""
    };
  },
  created() {
    this.getRoleList();
  },
  methods: {
    async getRoleList() {
      const res = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色数据失败");
      this.roleList = res.data;
    },
    async removeRoleById(role, id) {
      const isConfirm = await this.$confirm(
        "此操作将永久删除这一权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
        // 点击取消时，通过catch获取取消信息
      ).catch(err => err);
      if (isConfirm == "cancel") return this.$message.info("操作已取消");
      if (isConfirm == "confirm") {
        const res = await this.$http.delete(`roles/${role.id}/rights/${id}`);

        if (res.meta.status != 200) return this.$message.error("删除数据失败");
        this.$message.success("删除数据成功");

        role.children = res.data;
      }
    },
    async showRightDialog(role) {
      // 将角色id保存起来
      this.roleId = role.id;
      const res = await this.$http.get("rights/tree");
      if (res.meta.status != 200)
        return this.$message.error("获取权限列表失败");
      this.rightslist = res.data;
      this.leafKeysArry = [];
      this.getLeafKeys(role, this.leafKeysArry);
      // 控制弹窗
      this.rightsDialogVisible = true;
    },
    // 通过递归函数取出所有三级节点的id
    getLeafKeys(node, arr) {
      if (!node.children) return arr.push(node.id);
      node.children.forEach(item => this.getLeafKeys(item, arr));
    },
    async allotRights() {
      // 获取节点id值并拼接
      const checkedId = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ].join(",");
      const res = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: checkedId
      });
      if (res.meta.status != 200) return this.$message.error("分配权限失败");
      this.$message.success("分配权限成功");
      this.rightsDialogVisible = false;
      this.getRoleList();
    }
  }
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>